<script setup lang="ts">
import { Download, RefreshRight, Refresh } from "@element-plus/icons-vue"
import { computed, reactive, ref, watch } from "vue"
import { IGetMultiConditionQueryRequestData, IGetMultiConditionQueryResponseData } from "@/api/files/types/files"
import { usePagination } from "@/hooks/usePagination"
import { fileDownloadApi, getFileMultiConditionQueryApi } from "@/api/files"
import { IGetDepartmentData } from "@/api/department/types/department"
import { getDepartmentIdAndNameList } from "@/api/department"
import { GetProjectIdAndNameList } from "@/api/project"
import { IGetProjectIdAndNameResponseData } from "@/api/project/types/project"
import { useUserStore } from "@/store/modules/user"
import { openDownload } from "@/utils"
import { IUserInfoData } from "@/api/login/types/login"
import { getAdminByNameDataApi } from "@/api/admin"
import { IGetAdminByNameData } from "@/api/admin/types/admin"

const loading = ref(false)
const userStore = useUserStore()
const userInfo = userStore.userInfo as IUserInfoData
const searchData = reactive<IGetMultiConditionQueryRequestData>({
  name: "",
  theYear: "",
  projectId: undefined,
  departmentId: userInfo.departmentId,
  auditStatus: undefined,
  isNecessary: undefined,
  uploaderId: undefined
})
// 查询
const necessaryOptions = [
  {
    label: "补充资料",
    value: 0
  },
  {
    label: "必要资料",
    value: 1
  }
]

const auditStatus = [
  {
    label: "未审核",
    value: 0
  },
  {
    label: "驳回",
    value: 1
  },
  {
    label: "通过",
    value: 2
  }
]

const FilesData = ref<IGetMultiConditionQueryResponseData[]>([])
const DepartmentData = ref<IGetDepartmentData[]>([])
const ProjectData = ref<IGetProjectIdAndNameResponseData[]>([])
const { paginationData, handleCurrentChange, handleSizeChange } = usePagination()
const refreshing = ref(false)
const getFilesDataList = () => {
  if (refreshing.value) return
  loading.value = true
  refreshing.value = true
  getFileMultiConditionQueryApi({ page: paginationData.currentPage, size: paginationData.pageSize }, searchData)
    .then((res) => {
      FilesData.value = res.data.list
      paginationData.total = res.data.total
    })
    .catch(() => {
      FilesData.value = []
    })
    .finally(() => {
      refreshing.value = false
      loading.value = false
    })
}
defineExpose({ getFilesDataList })

const getDepartmentDataList = () => {
  getDepartmentIdAndNameList({ name: "", departmentId: userInfo.departmentId })
    .then((res) => {
      DepartmentData.value = res.data.list
    })
    .catch(() => {
      DepartmentData.value = []
    })
}
getDepartmentDataList()

const getProjectDataList = () => {
  GetProjectIdAndNameList({ name: "", departmentId: searchData.departmentId })
    .then((res) => {
      ProjectData.value = res.data.list
    })
    .catch(() => {
      ProjectData.value = []
    })
}
getProjectDataList()
// const handleSearch = () => {
//   if (paginationData.currentPage === 1) {
//     getFilesDataList()
//   }
//   paginationData.currentPage = 1
// }
const resetSearch = () => {
  searchData.name = ""
  searchData.projectId = undefined
  searchData.isNecessary = undefined
  searchData.departmentId = undefined
  searchData.theYear = ""
  searchData.auditStatus = undefined
  if (paginationData.currentPage === 1) {
    getFilesDataList()
  }
  paginationData.currentPage = 1
}

const handleRefresh = () => {
  getFilesDataList()
}

// 下载
const handleDownload = (data: IGetMultiConditionQueryResponseData) => {
  fileDownloadApi(userStore.userInfo!.id, [data.id]).then((res) => {
    openDownload(res.blob, res.fileName)
  })
}
const downloadItems = ref<IGetMultiConditionQueryResponseData[]>([])
const downloadIds = computed(() => {
  return downloadItems.value.map((item) => item.id)
})
const handleBatchDownload = () => {
  loading.value = true
  fileDownloadApi(userStore.userInfo!.id, downloadIds.value).then((res) => {
    openDownload(res.blob, res.fileName)
    loading.value = false
  })
}
const handleSelectionChange = (val: IGetMultiConditionQueryResponseData[]) => {
  downloadItems.value = val
}

const AdminData = ref<IGetAdminByNameData[]>([])

const getAdminData = () => {
  getAdminByNameDataApi({ name: "", departmentId: searchData.departmentId }).then((res) => {
    AdminData.value = res.data.users
  })
}
getAdminData()
watch([() => paginationData], getFilesDataList, { deep: true })

watch(
  [
    () => searchData.theYear,
    () => searchData.isNecessary,
    () => searchData.auditStatus,
    () => searchData.projectId,
    () => searchData.uploaderId
  ],
  getFilesDataList,
  {
    deep: true,
    immediate: true
  }
)

watch([() => searchData.departmentId], () => {
  searchData.uploaderId = undefined
  getAdminData()
  getProjectDataList()
  getFilesDataList()
})
</script>

<template>
  <div class="app-container" v-loading="loading">
    <!-- <el-card shadow="never" class="search-wrapper">
      <el-form ref="searchFormRef" :inline="true" :model="searchData">
        <el-form-item prop="name" label="文件名称">
          <el-input v-model="searchData.name" placeholder="请输入" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="handleSearch">查询</el-button>
          <el-button :icon="Refresh" @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card> -->

    <el-card shadow="never" class="my-5">
      <el-form inline ref="inlineFormRef" :model="searchData">
        <el-form-item v-if="userInfo.authority === '2'" prop="departmentId" label="办学单位">
          <el-select filterable v-model="searchData.departmentId" placeholder="选择办学单位">
            <el-option v-for="item in DepartmentData" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item prop="uploaderId" label="上传者">
          <el-select filterable v-model="searchData.uploaderId" placeholder="选择上传者">
            <el-option v-for="item in AdminData" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item prop="departmentId" label="培训项目">
          <el-select filterable v-model="searchData.projectId" placeholder="选择培训项目">
            <el-option v-for="item in ProjectData" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item prop="year" label="立项年度">
          <el-date-picker v-model="searchData.theYear" type="year" value-format="YYYY" placeholder="选择立项年度" />
        </el-form-item>
        <el-form-item prop="year" label="审核状态">
          <el-select filterable v-model="searchData.auditStatus" placeholder="选择审核状态">
            <el-option v-for="item in auditStatus" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item prop="year" label="资料类型">
          <el-select filterable v-model="searchData.isNecessary" placeholder="选择资料类型">
            <el-option v-for="item in necessaryOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Refresh" @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <el-card shadow="never">
      <div class="flex justify-between">
        <div>
          <el-button type="primary" :disabled="downloadIds.length === 0" :icon="Download" @click="handleBatchDownload">
            批量下载
          </el-button>
        </div>
        <div>
          <el-tooltip content="刷新表格">
            <el-button type="primary" :icon="RefreshRight" circle @click="handleRefresh" />
          </el-tooltip>
        </div>
      </div>
      <div class="mt-5">
        <el-table @selection-change="handleSelectionChange" :data="FilesData">
          <el-table-column type="selection" width="55" />
          <el-table-column prop="name" :show-overflow-tooltip="true" label="文件名" align="center" />
          <el-table-column prop="theYear" label="立项年度" align="center" />
          <el-table-column prop="departmentName" label="机构名称" align="center" />
          <el-table-column prop="projectName" label="项目名称" align="center" />
          <el-table-column prop="isNecessary" label="是否必须" align="center">
            <template #default="scope">
              {{ scope.row.isNecessary === 0 ? "否" : "是" }}
            </template>
          </el-table-column>
          <el-table-column prop="auditStatus" label="审核状态" align="center">
            <template #default="scope">
              <el-tag :type="scope.row.auditStatus === 0 ? '' : scope.row.auditStatus === 1 ? 'danger' : 'success'">
                {{ scope.row.auditStatus === 0 ? "未审核" : scope.row.auditStatus === 1 ? "驳回" : "通过" }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="cause" label="驳回原因" align="center" />
          <el-table-column prop="note" label="备注" align="center" />
          <el-table-column fixed="right" label="操作" width="220" align="center">
            <template #default="scope">
              <el-button type="primary" text bg size="small" @click="handleDownload(scope.row)">下载</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="mt-5">
        <el-pagination
          background
          :layout="paginationData.layout"
          :page-sizes="paginationData.pageSizes"
          :total="paginationData.total"
          :page-size="paginationData.pageSize"
          :currentPage="paginationData.currentPage"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<style scoped lang="scss"></style>
